﻿namespace CloudNinja.Metering.Common
{
    using System;
    using System.Text.RegularExpressions;

    public class Helper
    {
        public static string GetTenantId(string source, string tenantIdentifierPattern)
        {
            var openBracketLoc = tenantIdentifierPattern.IndexOf('{');
            var closeBracketLoc = tenantIdentifierPattern.IndexOf('}');

            if (openBracketLoc < 0 || closeBracketLoc < 0 || openBracketLoc > closeBracketLoc)
            {
                return string.Empty;
            }

            var parts = tenantIdentifierPattern.Split(new[] { '{', '}' });

            // Tenant ID pattern shuld be somestring|tenantid_regex|someotherstring.
            // Example: {.*}.thecloudninja.com denotes anything between two |'s is a tenantID
            if (parts.Length == 3)
            {
                if (!string.IsNullOrEmpty(parts[0]))
                {
                    var startRegex = new Regex("^" + parts[0]);
                    if (!startRegex.IsMatch(source))
                    {
                        return string.Empty;
                    }

                    source = startRegex.Replace(source, string.Empty);
                }

                if (!string.IsNullOrEmpty(parts[2]))
                {
                    var endRegex = new Regex(parts[2] + "$");
                    if (!endRegex.IsMatch(source))
                    {
                        return string.Empty;
                    }

                    source = endRegex.Replace(source, string.Empty);
                }

                if (!string.IsNullOrEmpty(source))
                {
                    var regex = new Regex(parts[1]);

                    if (regex.IsMatch(source))
                    {
                        return source;
                    }
                }
            }

            return string.Empty;
        }

        public static void Guard(TimeSpan interval, string intervalName)
        {
            if (interval.Equals(TimeSpan.Zero))
            {
                throw new ArgumentOutOfRangeException(intervalName);
            }
        }

        public static void Guard(object parameter, string parameterName)
        {
            if (parameter == null)
            {
                throw new ArgumentOutOfRangeException(parameterName);
            }
        }

        public static void Guard(string parameter, string parameterName)
        {
            if (string.IsNullOrEmpty(parameter))
            {
                throw new ArgumentOutOfRangeException(parameterName);
            }
        }
    }
}